import { useCallback } from 'react';
import { useEffectRef } from '.';

function useGetter(object, keys) {
  const objectRef = useEffectRef(object);
  const keysRef = useEffectRef(keys);

  return useCallback(() => {
    let { current: target } = objectRef;
    const keyList = keysRef.current?.slice() ?? [];

    for (const key of keyList) {
      target = target?.[key];
      if (target == null) return null;
    }

    return target ?? null;
  }, []);
}

export default useGetter;
